from datetime import datetime

from flask import abort
from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session

from info import constants, db
from info.models import User, News, Comment, CommentLike
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import news_blu




@news_blu.route('/followed_user',methods=["POST"])
@user_login_data
def followed_user():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    user_id = request.json.get("user_id")
    action = request.json.get("action")

    if not all([user_id,action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ("follow", "unfollow"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        user_id = int(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        target_user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询失败")

    if not target_user:
        return jsonify(errno=RET.NODATA, errmsg="未查询到用户数据")

    if action == "follow":

        if user.followed.filter(User.id == user.id).count() > 0:
            return jsonify(errno=RET.DATAEXIST, errmsg="当前已关注")

        user.followed.append(target_user)

    else:
        if user.followed.filter(User.id == user.id).count() > 0:
            user.followed.remove(target_user)

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存错误")

    return jsonify(errno=RET.OK, errmsg="操作成功")




@news_blu.route('/comment_like',methods=['POST'])
@user_login_data
def comment_like():
    """评论点赞"""
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

#    news_id = request.json.get('news_id')
    comment_id = request.json.get('comment_id')
    action = request.json.get('action')

    if not all([ comment_id,action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
#        news_id = int(news_id)
        comment_id = int(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ["add","remove"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    comment = None
    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not comment:
        return jsonify(errno=RET.NODATA, errmsg="评论不存在")

    if action == 'add':
        comment_like_model = CommentLike.query.filter(CommentLike.comment_id == comment_id,CommentLike.user_id == user.id).first()
        if not comment_like_model:
            comment_like_model = CommentLike()
            comment_like_model.user_id = user.id
            comment_like_model.comment_id = comment_id

            comment.like_count += 1
            db.session.add(comment_like_model)

    else:
        comment_like_model = CommentLike.query.filter(CommentLike.comment_id == comment_id,CommentLike.user_id == user.id).first()
        if comment_like_model:
            db.session.delete(comment_like_model)
            comment.like_count -= 1

    try:

        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg="数据库操作失败")

    return jsonify(errno=RET.OK, errmsg="OK")


@news_blu.route('/news_comment',methods=['POST'])
@user_login_data
def news_comment():
    """
        评论新闻或者回复某条新闻下指定的评论
        :return:
    """

    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    # 1. 取到请求参数
    news_id = request.json.get("news_id")
    comment_content = request.json.get("comment")
    parent_id = request.json.get("parent_id")

    # 2. 判断参数
    if not all([news_id, comment_content]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        news_id = int(news_id)
        if parent_id:
            parent_id = int(parent_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 查询新闻，并判断新闻是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查询到新闻数据")

    # 3. 初始化一个评论模型，并且赋值
    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news_id
    comment.content = comment_content
    if parent_id:
        comment.parent_id = parent_id

    # 添加到数据库
    # 为什么要自己去commit()?，因为在return的时候需要用到 comment 的 id
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()

    return jsonify(errno=RET.OK, errmsg="OK", data=comment.to_dict())
    # user = g.user
    # if not user:
    #     return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    #
    # news_id = request.json.get('news_id')
    # content = request.json.get('comment')
    # parent_id = request.json.get('parent_id')
    #
    # if not all([news_id, content]):
    #     return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    #
    # try:
    #     news_id = int(news_id)
    # except Exception as e:
    #     current_app.logger.error(e)
    #     return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    #
    # news = None
    # try:
    #     news = News.query.get(news_id)
    # except Exception as e:
    #     current_app.logger.error(e)
    #     return jsonify(errno=RET.DBERR, errmsg="查询错误")
    #
    # if not news:
    #     return jsonify(errno=RET.NODATA, errmsg="未查询到新闻数据")
    #
    # comment = Comment()
    # comment.user_id = user.id
    # comment.news_id = news_id
    # comment.content = content
    # comment.create_time = datetime.now()
    # if parent_id:
    #     comment.parent_id = parent_id
    #
    # try:
    #     db.session.add(comment)
    #     db.session.commit()
    # except Exception as e:
    #     db.session.rollback()
    #     current_app.logger.error(e)
    #     return jsonify(errno=RET.DBERR,errmsg="保存数据库失败")
    #
    # return jsonify(errno=RET.OK,errmsg="评论成功",data=comment.to_dict())

@news_blu.route('/collect_news',methods=['POST'])
@user_login_data
def collect_news():

    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    news_id = request.json.get('news_id')
    action = request.json.get('action')

    if not all([news_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")

    if action not in ["collect","cancel_collect"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查询到新闻数据")

    if action == 'collect':

        if news not in user.collection_news:
            user.collection_news.append(news)

    else:
        if news in user.collection_news:
            user.collection_news.remove(news)

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存失败")


    return jsonify(errno=RET.OK,errmsg="ok")

@news_blu.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):

    user = g.user

    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.looger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")

    news_list = None
    try:
        # 获取右侧点击排行数据
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.HOME_PAGE_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='数据库错误')

    news_dict_li = []
    for new in news_list:
        news_dict_li.append(new.to_dict())

    # 获取新闻详情数据
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.looger.error(e)
        abort(404)
    # 给当前新闻添加点击量
    news.clicks += 1

    # 是否收藏
    is_collected = False

    if user:
        # 当前新闻是否在我收藏的新闻列表中
        if news in user.collection_news:
            is_collected = True

    comments = None
    try:
        # 获取当前新闻的评论信息
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)

    comment_like_ids = []
    if g.user:
        try:
            # 1.查询这条新闻的所有评论id
            comment_ids = [comment.id for comment in comments]
            # 2.查询这些评论哪条被当前用户点击
            comment_likes = CommentLike.query.filter(CommentLike.comment_id.in_(comment_ids),CommentLike.user_id == g.user.id).all()

            comment_like_ids = [comment_like.comment_id for comment_like in comment_likes]
        except Exception as e:
            current_app.logger.error(e)

    comment_dict_li = []

    for comment in comments:
        comment_dict = comment.to_dict()
        comment_dict["is_like"] = False
        if comment.id in comment_like_ids:
            comment_dict["is_like"] = True
        comment_dict_li.append(comment_dict)

    # 当前登录用户是否关注当前新闻作者
    is_followed = False

    # if user.followed.filter(User.id == news.user_id).count() > 0:
    #     is_followed = True

    # if 当前新闻有作者，并且 当前登录用户已关注过这个用户
    if news.user and user:
        # 如果新闻作者 在当前用户的关注中
        if news.user in user.followed:
            is_followed = True

    data = {
        'user':user.to_dict() if user else None,# 用户信息
        'news_info':news.to_dict(), # 新闻信息
        'news':news_dict_li, # 右侧6条新闻列表
        'is_collected':is_collected,# 是否收藏
        'comments':comment_dict_li, # 品论
        'is_followed':is_followed
    }
    return render_template("news/detail.html",data=data)